// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import ResMgr from "../common/ResMgr";
import StartUp from "../StartUp";

const {ccclass, property} = cc._decorator;


@ccclass
export default class PoolMgr extends cc.Component {

    protected static _instance:PoolMgr = null;
    public static get instance():PoolMgr {
        if (PoolMgr._instance == null) {
            let node = new cc.Node();
            node.name = "PoolMgr";
            PoolMgr._instance = node.addComponent(PoolMgr);
            StartUp.instance.gameRoot.addChild(node);
        }
        return PoolMgr._instance;
    }

    public dict:Map<string, cc.Node[]> = new Map<string, cc.Node[]>();

    onLoad() {
        this.node.active = false;
    }

    public get(path:string, callback) {
        let nodeList = this.dict.get(path);
        let isEnough = nodeList != null && nodeList.length > 0;
        if (isEnough) {
            let node = nodeList[0];
            nodeList.splice(0, 1);
            node.active = true;
            node.removeFromParent(false);
            callback && callback(node);
        } else {
            ResMgr.loadPrefab(path, function(prefab){
                let ins = cc.instantiate(prefab);
                callback && callback(ins);
            }.bind(this))
        }
    }

    public ret(path:string, node:cc.Node) {
        node.active = false;
        node.setPosition(new cc.Vec2(0,0));
        node.removeFromParent(false);
        let nodeList = this.dict.get(path);
        if (nodeList == null) { 
            nodeList = [];
            this.dict.set(path, nodeList);
        }
        this.node.addChild(node);
        nodeList.push(node);
    }

    public clear() {
        this.dict.forEach((list, path)=>{
            for (let i = 0; i < list.length; i++) {
                this.node.removeChild(list[i]);
            }
            list.length = 0;
        })
        this.dict.clear();
    }

}

